import React, { useState } from "react";
import { View, StatusBar, Alert } from "react-native";
import { SafeAreaView } from "react-native-safe-area-context";
import { Link } from "expo-router";
import * as ImagePicker from "expo-image-picker";
import * as DocumentPicker from "expo-document-picker";
import {
  ArrowLeft,
  Smartphone,
  Image as ImageIcon,
  File,
  Camera,
  Music,
  MessageSquare,
  Send,
} from "lucide-react-native";
import { Button } from "~/components/ui/button";
import { Text } from "~/components/ui/text";
import { Textarea } from "~/components/ui/textarea";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogFooter,
  DialogTrigger,
  DialogClose,
} from "~/components/ui/dialog";

const DeviceScreen = () => {
  const [textMessage, setTextMessage] = useState("");

  const handleTextSend = () => {
    if (textMessage.trim()) {
      Alert.alert("Success", `Text message sent: "${textMessage}"`, [
        {
          text: "OK",
          onPress: () => {
            setTextMessage("");
          },
        },
      ]);
      // Here you would handle sending the text message
      console.log("Sending text:", textMessage);
    } else {
      Alert.alert("Error", "Please enter some text to send");
    }
  };

  const handlePhotosAndVideos = async () => {
    try {
      // Request permissions
      const { status } =
        await ImagePicker.requestMediaLibraryPermissionsAsync();
      if (status !== "granted") {
        Alert.alert(
          "Permission needed",
          "Sorry, we need camera roll permissions to make this work!",
        );
        return;
      }

      // Launch image picker
      const result = await ImagePicker.launchImageLibraryAsync({
        mediaTypes: ImagePicker.MediaTypeOptions.All,
        allowsEditing: true,
        aspect: [4, 3],
        quality: 1,
        allowsMultipleSelection: true,
      });

      if (!result.canceled) {
        Alert.alert(
          "Success",
          `Selected ${result.assets?.length || 1} item(s)`,
        );
        // Here you would handle sending the selected media
        console.log("Selected media:", result.assets);
      }
    } catch (error) {
      Alert.alert("Error", "Failed to access media library");
      console.error("Media picker error:", error);
    }
  };

  const handleFiles = async () => {
    try {
      const result = await DocumentPicker.getDocumentAsync({
        type: "*/*",
        multiple: true,
        copyToCacheDirectory: true,
      });

      if (!result.canceled) {
        Alert.alert(
          "Success",
          `Selected ${result.assets?.length || 1} file(s)`,
        );
        // Here you would handle sending the selected files
        console.log("Selected files:", result.assets);
      }
    } catch (error) {
      Alert.alert("Error", "Failed to access files");
      console.error("Document picker error:", error);
    }
  };

  const handleCamera = async () => {
    try {
      // Request permissions
      const { status } = await ImagePicker.requestCameraPermissionsAsync();
      if (status !== "granted") {
        Alert.alert(
          "Permission needed",
          "Sorry, we need camera permissions to make this work!",
        );
        return;
      }

      // Launch camera
      const result = await ImagePicker.launchCameraAsync({
        allowsEditing: true,
        aspect: [4, 3],
        quality: 1,
        mediaTypes: ImagePicker.MediaTypeOptions.All,
      });

      if (!result.canceled) {
        Alert.alert("Success", "Photo/video captured successfully!");
        // Here you would handle sending the captured media
        console.log("Captured media:", result.assets[0]);
      }
    } catch (error) {
      Alert.alert("Error", "Failed to access camera");
      console.error("Camera error:", error);
    }
  };

  const handleAudio = async () => {
    try {
      // For now, show a placeholder for audio functionality
      Alert.alert(
        "Audio Recording",
        "Audio recording feature will be implemented here. This would allow recording and sending audio messages.",
        [
          {
            text: "OK",
            onPress: () => console.log("Audio feature placeholder"),
          },
        ],
      );
    } catch (error) {
      Alert.alert("Error", "Failed to access audio recording");
      console.error("Audio error:", error);
    }
  };

  const options = [
    {
      title: "Text",
      description: "Send a text message",
      icon: <MessageSquare size={28} color="#fff" />,
      bgColor: "bg-green-500",
      isText: true,
    },
    {
      title: "Photos and videos",
      description: "Send media saved on this phone",
      icon: <ImageIcon size={28} color="#fff" />,
      bgColor: "bg-purple-500",
      onPress: handlePhotosAndVideos,
    },
    {
      title: "Files",
      description: "Send files saved by any app",
      icon: <File size={28} color="#fff" />,
      bgColor: "bg-blue-500",
      onPress: handleFiles,
    },
    {
      title: "Camera",
      description: "Take and send a new photo",
      icon: <Camera size={28} color="#fff" />,
      bgColor: "bg-red-500",
      onPress: handleCamera,
    },
    {
      title: "Audio",
      description: "Send audio saved on this phone",
      icon: <Music size={28} color="#fff" />,
      bgColor: "bg-orange-500",
      onPress: handleAudio,
    },
  ];

  return (
    <SafeAreaView className="flex-1 bg-gray-50">
      <StatusBar barStyle="dark-content" backgroundColor="#f9fafb" />

      {/* Header */}
      <View className="flex-row items-center px-4 py-3">
        <Link href="/" asChild>
          <Button variant="ghost" size="icon" className="mr-2">
            <ArrowLeft size={24} color="#333" />
          </Button>
        </Link>
      </View>

      {/* Device Info */}
      <View className="items-center py-8">
        <View className="w-32 h-32 bg-purple-600 rounded-full items-center justify-center mb-6">
          <Smartphone size={64} color="#fff" />
        </View>
        <Text className="text-3xl font-bold text-gray-900 mb-2">OP5A29L1</Text>
        <Text className="text-lg text-gray-500">Your phone</Text>
      </View>

      {/* Divider */}
      <View className="h-px bg-gray-200 mx-4 mb-6" />

      {/* Options */}
      <View className="px-4 gap-y-10 flex flex-col">
        {options.map((option, index) => {
          if (option.isText) {
            return (
              <Dialog key={index}>
                <DialogTrigger asChild>
                  <Button
                    variant="ghost"
                    className="flex-row items-center py-4 h-auto justify-start bg-transparent w-full"
                  >
                    <View
                      className={`w-16 h-16 ${option.bgColor} rounded-full items-center justify-center mr-4`}
                    >
                      {option.icon}
                    </View>
                    <View className="flex-1 items-start">
                      <Text className="text-lg font-semibold text-gray-900 mb-1">
                        {option.title}
                      </Text>
                      <Text className="text-gray-500">
                        {option.description}
                      </Text>
                    </View>
                  </Button>
                </DialogTrigger>
                <DialogContent className="w-full max-w-lg mx-4 bg-white">
                  <DialogHeader>
                    <DialogTitle>Send Text Message</DialogTitle>
                  </DialogHeader>
                  <View className="py-4">
                    <Textarea
                      value={textMessage}
                      onChangeText={setTextMessage}
                      placeholder="Enter your message..."
                      numberOfLines={8}
                      className="min-h-[200px]"
                    />
                  </View>
                  <DialogFooter className="flex-row gap-3">
                    <DialogClose asChild>
                      <Button
                        variant="outline"
                        className="flex-1"
                        onPress={() => setTextMessage("")}
                      >
                        <Text>Cancel</Text>
                      </Button>
                    </DialogClose>
                    <DialogClose asChild>
                      <Button
                        onPress={handleTextSend}
                        className="flex-1 flex-row"
                        disabled={!textMessage.trim()}
                      >
                        <Send size={16} color="#000" />
                        <Text className="text-black font-semibold ml-2">
                          Send
                        </Text>
                      </Button>
                    </DialogClose>
                  </DialogFooter>
                </DialogContent>
              </Dialog>
            );
          }

          return (
            <Button
              key={index}
              variant="ghost"
              className="flex-row items-center py-4 h-auto justify-start bg-transparent w-full"
              onPress={option.onPress}
            >
              <View
                className={`w-16 h-16 ${option.bgColor} rounded-full items-center justify-center mr-4`}
              >
                {option.icon}
              </View>
              <View className="flex-1 items-start">
                <Text className="text-lg font-semibold text-gray-900 mb-1">
                  {option.title}
                </Text>
                <Text className="text-gray-500">{option.description}</Text>
              </View>
            </Button>
          );
        })}
      </View>
    </SafeAreaView>
  );
};

export default DeviceScreen;

